from ast import Raise
from charset_normalizer import logging
import numpy as np

# 根据name和index找到某个数据str:x
def name_indx_2_x(name,num,data,x):
    index = data['ct_name'].index(name)
    num_set = data[data['split']+'_group'][index]
    x_set = data[data['split']+'_'+x][index]
    index_of_num = np.where(np.array(num_set) == int(num))[0]
    if(len(set(np.array(x_set)[index_of_num]))==1):
        return list(set(np.array(x_set)[index_of_num]))[0]
    else:
        logging.warning("同个结节的{0}不一致，属于数据错误".format(x))
        return list(set(np.array(x_set)[index_of_num]))[0]

# 根据name和index找到某个数据str:x,该x数据有多个
def name_indx_2_xpp(name,num,data,x):
    index = data['ct_name'].index(name)
    num_set = data[data['split']+'_group'][index]
    x_set = data[data['split']+'_'+x][index]
    index_of_num = np.where(np.array(num_set) == int(num))[0]
    return list(set(np.array(x_set)[index_of_num]))
# 根据name和num找到box
def name_num_2_box(name,num,data):
    label = 0
    index = data['ct_name'].index(name)
    num_set = data[data['split']+'_group'][index]
    boxes_set = data[data['split']+'_boxes'][index]
    layer_set = data[data['split']+'_layer'][index]
    index_of_num = np.where(np.array(num_set) == num)[0]
    boxes_of_single_nodule = list(np.array(boxes_set,dtype=object)[index_of_num])
    layer_of_single_nodule = list(np.array(layer_set)[index_of_num])
    new_boxes_of_single_nodule = []
    new_layer_of_single_nodule = []
    # layer重复，说明又有box又有多边形
    if(len(set(layer_of_single_nodule)) !=  len(layer_of_single_nodule)):
        for i in range(len(boxes_of_single_nodule)):
            if(len(np.array(boxes_of_single_nodule[i]).shape)==1):
                pass
            # 只保留多边形
            elif(len(np.array(boxes_of_single_nodule[i]).shape)==2):
                new_boxes_of_single_nodule.append(boxes_of_single_nodule[i])
                new_layer_of_single_nodule.append(layer_of_single_nodule[i])
        # 如果经过上述处理还是有多余的层，那说明数据错了
        if(len(set(new_layer_of_single_nodule)) !=  len(new_layer_of_single_nodule)):
            logging.warning("同个结节的层标号重复，数据错误")
            return {layer_of_single_nodule[i]:boxes_of_single_nodule[i] for i in range(len(boxes_of_single_nodule))}
        return {new_layer_of_single_nodule[i]:new_boxes_of_single_nodule[i] for i in range(len(new_layer_of_single_nodule))}
        
    else:
        return {layer_of_single_nodule[i]:boxes_of_single_nodule[i] for i in range(len(boxes_of_single_nodule))}

def find_label(nodule,gt_data,ai_data,mode = 0):
    gt_labeles = []
    ai_labeles = []
    label_dict = {}
    for info in nodule:
        [ct_name,gt_num,ai_num] = info.split('_')
        if(gt_num != 'xx'):
            gt_num = int(gt_num)
            gt_label = name_indx_2_x(ct_name,gt_num,gt_data,'labels')
        else:
            gt_label = None
        if(ai_num != 'xx'):
            ai_num = int(ai_num)
            ai_label = name_indx_2_x(ct_name,ai_num,ai_data,'labels')
        else:
            ai_label = None
        gt_labeles.append(gt_label)
        ai_labeles.append(ai_label)
        label_dict[info] = {"gt_label":gt_label,"ai_label":ai_label}
    if(mode == 0):
        return gt_labeles,ai_labeles
    else:
        return label_dict

def find_box(TP_nodule,gt_data,ai_data):
    box_dict = {}
    for info in TP_nodule:
        [ct_name,gt_num,ai_num] = info.split('_')
        gt_num = int(gt_num)
        ai_num = int(ai_num)
        gt_boxes = name_num_2_box(ct_name,gt_num,gt_data)
        ai_boxes = name_num_2_box(ct_name,ai_num,ai_data)
        box_dict[info] = {"gt_boxes":gt_boxes,"ai_boxes":ai_boxes}
    return box_dict
    
def find_totalVolume(nodule,gt_data,ai_data):
    totalVolume_dict = {}
    for info in nodule:
        [ct_name,gt_num,ai_num] = info.split('_')
        if(gt_num != 'xx'):
            gt_num = int(gt_num)
            gt_totalVolume = name_indx_2_x(ct_name,gt_num,gt_data,'totalVolume')
        else:
            gt_totalVolume = None
        if(ai_num != 'xx'):
            ai_num = int(ai_num)
            ai_totalVolume = name_indx_2_x(ct_name,ai_num,ai_data,'totalVolume')
        else:
            ai_totalVolume = None
        totalVolume_dict[info] = {"gt_totalVolume":gt_totalVolume,"ai_totalVolume":ai_totalVolume}
    return totalVolume_dict

def find_mean_density(nodule,gt_data,ai_data):
    mean_density_dict = {}
    for info in nodule:
        [ct_name,gt_num,ai_num] = info.split('_')
        if(gt_num != 'xx'):
            gt_num = int(gt_num)
            gt_mean_density = name_indx_2_x(ct_name,gt_num,gt_data,'nodule_density')
        else:
            gt_mean_density = None
        if(ai_num != 'xx'):
            ai_num = int(ai_num)
            ai_mean_density = name_indx_2_x(ct_name,ai_num,ai_data,'nodule_density')
        else:
            ai_mean_density = None
        mean_density_dict[info] = {"gt_mean_density":gt_mean_density,"ai_mean_density":ai_mean_density}
    return mean_density_dict

def find_norpr_scores(nodule,ai_data):
    norpr_scores = {}
    for info in nodule:
        [ct_name,gt_num,ai_num] = info.split('_')
        if(ai_num != 'xx'):
            ai_num = int(ai_num)
            norpr = name_indx_2_x(ct_name,ai_num,ai_data,x='norpr')
            score = name_indx_2_x(ct_name,ai_num,ai_data,x='scores')
        else:
            score = None
        norpr_scores[info] = {"norpr":norpr,"ai_totalVolume":score}
    return norpr_scores
def find_layer(nodule,gt_data,ai_data):
    layer = {}
    for info in nodule:
        [ct_name,gt_num,ai_num] = info.split('_')
        if(gt_num != 'xx'):
            gt_num = int(gt_num)
            gt_layer = name_indx_2_xpp(ct_name,gt_num,gt_data,'layer')
        else:
            gt_layer = []
        if(ai_num != 'xx'):
            ai_num = int(ai_num)
            ai_layer = name_indx_2_xpp(ct_name,ai_num,ai_data,'layer')
        else:
            ai_layer = []
        layer[info] = list(set(ai_layer+gt_layer))
    return layer
